package com.sxt.core.consumer.scan.impl;

import java.lang.reflect.Field;
import java.util.List;

import com.sxt.core.anno.Ref;
import com.sxt.core.consumer.scan.RefObjectScanService;
import com.sxt.core.context.IocContext;
import com.sxt.core.proxy.MethodInvoke;
import com.sxt.core.utils.PackageScanUtil;
import com.sxt.core.utils.ProxyFactoryUtil;

public class RefObjectScanServiceImpl implements RefObjectScanService {
	
	@Override
	public void injectRefObject(String packages,IocContext iocContext) {
		List<String> classNames = PackageScanUtil.packageScan(packages);
		for (String className : classNames) {
			try {
				Class<?> clazz = Class.forName(className);
				Field[] fields = clazz.getDeclaredFields();
				for (Field field : fields) {
					Ref ref = field.getAnnotation(Ref.class);
					if(ref!=null) {
						Class<?> type = field.getType();
						Object proxy = ProxyFactoryUtil.createProxy(type, iocContext.getBean(MethodInvoke.class));
						field.setAccessible(true);
						Object bean = iocContext.getBean(clazz.getInterfaces()[0]);
						field.set(bean, proxy);
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
}
